import re
from middleware import MiddleWare


class CookieMiddleWare(MiddleWare):
    def process_request(self, request):  #
        if "Cookie" not in request:
            return

        cookie_str = request['Cookie']
        for kv in re.split(";\\s*", cookie_str):
            key, value = re.split("\\s*=\\s*", kv)
            request.cookies[key] = value

    def process_response(self, response):
        if response.cookies:
            for key in response.cookies:
                value = response.cookies[key]
                if isinstance(value, list):
                    for v in value:
                        response["Set-Cookie"] = "%s=%s" % (key, v)
                else:
                    response["Set-Cookie"] = "%s=%s" % (key, value)





